import { Navigate } from 'react-router-dom'

import { PageEmpty } from '@/components/PageEmpty'
import { RouteErrorBoundary } from '@/components/RouteErrorBoundary'
import { fetchUserInfo } from '@/globalStore/userInfo'
import { TRoute } from '../interface'
import { bizOms } from './biz.oms'
import { bizTms } from './biz.tms'
import { setTitle } from './utils'

/** 404 路由 */
const notFoundRoute: TRoute<true> = {
  path: '*',
  handle: { name: () => '该页面不存在' },
  element: setTitle(<PageEmpty type="notFound" />),
}

/** 路由表，集中统一配置，路由地址使用首字母小写驼峰命名法 */
let routes: TRoute[] = [
  {
    path: '/',
    handle: undefined,
    element: <Navigate to={import.meta.env.VITE_APP_HOME_ROUTE_PATH} replace />,
  },
  {
    path: '/track',
    handle: { name: () => 'Track' },
    lazy: async () => {
      const { Home } = await import('@/pOTB/Track')
      return { element: setTitle(<Home />) }
    },
  },
  {
    path: '/track/result',
    handle: { name: () => 'Track result' },
    lazy: async () => {
      const { List } = await import('@/pOTB/Track')
      return { element: setTitle(<List />) }
    },
  },
  {
    path: '/biz/',
    handle: undefined,
    loader: () => fetchUserInfo().then(() => null),
    lazy: async () => {
      const { Biz } = await import('@oBiz/Biz')
      return { element: setTitle(<Biz />) }
    },
    children: [
      ...($APP === 'OMS' ? bizOms : []), // OMS
      ...($APP === 'TMS' ? bizTms : []), // TMS
      { ...notFoundRoute },
    ],
  },
  { ...notFoundRoute },
]

// 路由表公共逻辑处理
routes = routes.map(item => {
  const loop = function <T>({ ...route }: TRoute<T>): TRoute<T> {
    if (!route.errorElement) route.errorElement = <RouteErrorBoundary /> // 异常反馈
    if (route.children) {
      route.children = route.children.map(loop)
    }
    return route
  }
  return loop(item)
})

export { routes }
